<template>
  <el-main>
    <sys-dialog
      :title="sysDialog.title"
      :width="sysDialog.width"
      :height="sysDialog.height"
      :visible="sysDialog.visible"
      @onClose="sysDialogClose"
      @onConfirm="sysDialogConfirm"
    >
      <div slot="content">
        <el-form
          ref="entityForm"
          :model="entityModel"
          :rules="entityRules"
          :inline="true"
          label-width="80px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="parentId" label="上级部门">
                <el-tree
                  ref="parentTree"
                  accordion
                  highlight-current
                  default-expand-all
                  :data="parentTreeData"
                  :props="parentTreeProps"
                  node-key="id"
                  class="parentTree"
                  @node-click="parentTreeNodeClick"
                />
              </el-form-item>
              <el-form-item>
                <span style="color:red">* 注意：未选择默认为顶级部门</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="部门名称">
                <el-input v-model="entityModel.name" placeholder="请输入部门名称" />
              </el-form-item>
              <el-form-item prop="manager" label="部门经理">
                <el-input v-model="entityModel.manager" placeholder="请输入部门经理" />
              </el-form-item>
              <el-form-item prop="phone" label="部门电话">
                <el-input v-model="entityModel.phone" placeholder="请输入部门电话" />
              </el-form-item>
              <el-form-item prop="email" label="部门邮箱">
                <el-input v-model="entityModel.email" placeholder="请输入部门邮箱" />
              </el-form-item>
              <el-form-item prop="orderNum" label="显示顺序">
                <el-input-number v-model="entityModel.orderNum" :min="1" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </sys-dialog>
    <el-form
      ref="searchForm"
      :model="searchModel"
      :rules="searchRules"
      :inline="true"
      label-width="80px"
    >
      <el-form-item v-if="checkPermission(['sys:department:search'])" prop="name">
        <el-input v-model="searchModel.name" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item>
        <el-button v-if="checkPermission(['sys:department:search'])" icon="el-icon-search" @click="searchHandler()">查询</el-button>
        <el-button v-if="checkPermission(['sys:department:search'])" icon="el-icon-delete" @click="resethHandler()">重置</el-button>
        <el-button v-if="checkPermission(['sys:department:add'])" type="primary" icon="el-icon-plus" @click="addHandler()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="tableList"
      :height="tableHeight"
      row-key="id"
      border
      stripe
      highlight-current-row
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="部门名称" />
      <el-table-column prop="manager" label="部门经理" />
      <el-table-column prop="phone" label="部门电话" />
      <el-table-column prop="email" label="部门邮箱" />
      <el-table-column prop="orderNum" label="显示顺序" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="250">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['sys:department:update'])" type="primary" icon="el-icon-edit-outline" @click="updateHandler(scope.row)">编辑</el-button>
          <el-button v-if="checkPermission(['sys:department:delete'])" type="danger" icon="el-icon-close" @click="deleteHandler(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-main>
</template>

<script>
import checkPermission from '@/utils/permission'
import { add, deleteById, update, getById, getList, search } from '@/api/sysDepartment'
import SysDialog from '@/components/SysDialog'
export default {
  name: 'SystemDepartment',
  components: {
    SysDialog
  },
  props: {},
  data() {
    return {
      loading: false,
      tableList: [],
      tableHeight: 0,
      sysDialog: {
        title: '系统提示',
        type: 'add',
        visible: false,
        width: 590,
        height: 360
      },
      entityModel: {
        id: null,
        name: null,
        phone: null,
        email: null,
        manager: null,
        parentId: 0,
        orderNum: 0,
        createTime: null
      },
      entityRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入部门名称' }],
        manager: [{ required: true, trigger: 'blur', message: '请输入部门经理' }]
      },
      searchModel: {
        name: null
      },
      searchRules: {
        name: [{ required: true, trigger: 'blur', message: '请输入部门名称' }]
      },
      parentTreeData: [],
      parentTreeProps: {
        label: 'name',
        children: 'children'
      },
      parentTreeCheckedId: null
    }
  },
  created() {
    this.fetchList()
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 185
    })
  },
  methods: {
    checkPermission,
    fetchList() {
      this.loading = true
      getList().then(response => {
        if (response.code === 200) {
          this.tableList = response.data
          this.loading = false
        }
      })
    },
    sysDialogOpen(title, type) {
      // 设置窗口属性
      this.sysDialog.title = title
      this.sysDialog.type = type
      this.sysDialog.visible = true
      // 重置表单内容
      this.$nextTick(() => {
        this.$refs.entityForm.resetFields()
        this.entityModel.id = null
      })
      // 获取部门列表
      getList().then(response => {
        if (response.code === 200) {
          this.parentTreeData = response.data
        }
      })
    },
    sysDialogClose() {
      this.sysDialog.visible = false
      this.parentTreeCheckedId = null
    },
    sysDialogConfirm() {
      this.$refs.entityForm.validate(valid => {
        if (valid) {
          if (this.sysDialog.type === 'add') {
            add(this.entityModel).then(response => {
              if (response.code === 200) {
                this.$notify.success({ title: '系统提示', message: response.msg })
                this.fetchList()
                this.sysDialogClose()
              }
            })
          }
          if (this.sysDialog.type === 'update') {
            update(this.entityModel).then(response => {
              if (response.code === 200) {
                this.$notify.success({ title: '系统提示', message: response.msg })
                this.fetchList()
                this.sysDialogClose()
              }
            })
          }
        }
      })
    },
    parentTreeNodeClick(data) {
      const lastId = this.parentTreeCheckedId
      const currId = data.id
      if (currId === lastId) {
        this.$refs.parentTree.setCurrentKey(null)
        this.parentTreeCheckedId = null
        this.entityModel.parentId = 0
      } else {
        this.$refs.parentTree.setCurrentKey(currId)
        this.parentTreeCheckedId = currId
        this.entityModel.parentId = currId
      }
    },
    searchHandler() {
      this.$refs.searchForm.validate(valid => {
        if (valid) {
          this.loading = true
          search(this.searchModel).then(response => {
            if (response.code === 200) {
              this.tableList = response.data
              this.loading = false
            }
          })
        }
      })
    },
    resethHandler() {
      this.$refs.searchForm.resetFields()
      this.fetchList()
    },
    addHandler() {
      this.sysDialogOpen('新增系统部门', 'add')
    },
    updateHandler(row) {
      this.sysDialogOpen('修改系统部门', 'update')
      getById({ id: row.id }).then(response => {
        if (response.code === 200) {
          this.entityModel = response.data
          if (this.entityModel.parentId !== 0) {
            this.$refs.parentTree.setCurrentKey(this.entityModel.parentId)
            this.parentTreeCheckedId = this.entityModel.parentId
          }
        }
      })
    },
    deleteHandler(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById({ id: row.id }).then(response => {
          if (response.code === 200) {
            this.$notify.success({ title: '系统提示', message: response.msg })
            this.fetchList()
          }
        })
      }).catch(() => {
        console.log('取消删除')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.parentTree {
  width: 184px;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
}
</style>
